﻿using System;
using System.Windows.Forms;

namespace Grid {

	public class Grid : DataGridView {
		private int row = -1;
		private int column = -1;

		public string PrimaryKey { set; get; }

		public string UpdateTable { set; get; }

		public string EditForm { set; get; }

		public delegate void dataInsertEnd();

		// event declaration
		public event dataInsertEnd DataInsert;

		public DataGridViewRow getRow() {
			return base.CurrentRow;
		}

		public int SelectedIdFromTable() {
			if ( base.CurrentCell != null && base.CurrentRow != null ) {
				if ( PrimaryKey.Length > 1 ) {
					return Convert.ToInt32( base[PrimaryKey, curRow()].Value.ToString() );
				} else {
					return -1;
				}
			}
			return -1;
		}

		public int curRow() {
			return row;
		}

		public int curColum() {
			return column;
		}

		protected override void OnCreateControl() {
			base.MultiSelect = false;
			if ( EditForm != "" ) {
				base.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
				base.EditMode = DataGridViewEditMode.EditProgrammatically;
			}

			base.OnCreateControl();
		}

		protected override void OnMouseDoubleClick( MouseEventArgs e ) {
			base.OnMouseDoubleClick( e );
		}

		protected override void OnValidated( EventArgs e ) {
			base.OnValidated( e );
		}

		public void Edit() {
			try {
				if ( EditForm.Length > 1 ) {
					System.Reflection.Assembly asm = System.Reflection.Assembly.GetCallingAssembly();
					if ( asm != null ) {
						if ( SelectedIdFromTable() != -1 ) {
							Type t = asm.CreateInstance( EditForm, true ).GetType();
							Form frm = ( Form )Activator.CreateInstance( t, new object[] { SelectedIdFromTable() } );
							frm.ShowDialog();
							DataInsert.Invoke();
						}
					}
				}
			}
			catch ( Exception ex ) {
				MessageBox.Show( "Не постои форма за едитирање" );
				return;
			}
		}

		public void Insert() {
			try {
				if ( EditForm.Length > 1 ) {
					System.Reflection.Assembly asm = System.Reflection.Assembly.GetCallingAssembly();
					if ( asm != null ) {
						Form frm = ( Form )asm.CreateInstance( EditForm, true );
						frm.ShowDialog();
						DataInsert.Invoke();
					}
				}
			}
			catch ( Exception ex ) {
				MessageBox.Show( "Не постои форма за внес" );
				return;
			}
		}

		protected override void OnSelectionChanged( EventArgs e ) {
			if ( base.CurrentCell != null && base.CurrentRow != null ) {
				column = base.CurrentCell.ColumnIndex;
				row = base.CurrentRow.Index;
			}
			base.OnSelectionChanged( e );
		}
	}
}